package com.wl.wuliu.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wl.wuliu.entity.Driver;
import com.wl.wuliu.entity.SysUser;
import com.wl.wuliu.entity.Truck;
import com.wl.wuliu.exception.GlobalExceptionHandler;
import com.wl.wuliu.mapper.DriverMapper;
import com.wl.wuliu.mapper.TruckMapper;
import com.wl.wuliu.result.AjaxResult;
import com.wl.wuliu.service.DriverService;
import com.wl.wuliu.service.SysUserService;
import com.wl.wuliu.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @Author: gutaozhen
 * @Date: 2024/5/15
 */
@Service
public class DriverServiceImpl extends ServiceImpl<DriverMapper, Driver> implements DriverService {
    public static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @Autowired
    private DriverMapper driverMapper;
    @Autowired
    private TruckMapper truckMapper;
    @Autowired
    private SysUserService sysUserService;


    @Override
    public List<Driver> findList(Driver driver) {

        List<Driver> list = driverMapper.findList(driver);
        return list;
    }

    @Override
    public AjaxResult saveDriver(Driver driver) {

        driver.preInsert();
        save(driver);
        log.info("添加司机信息成功，id为：{}", driver.getId());

        return AjaxResult.success("添加成功！");
    }

    @Override
    public AjaxResult updateDriver(Driver driver) {

        log.info("修改司机信息，修改前的信息为：{}", driver);
        driver.preUpdate();
        updateById(driver);
        log.info("修改司机信息成功");

        return AjaxResult.success("修改成功！");
    }

    @Override
    public AjaxResult deleteDriver(String id) {

        //判断该司机是否有绑定的运输车信息，如果有不允许删除
        Map<String,Object> queryMap = new HashMap<>();
        queryMap.put("driver_id", id);
        List<Truck> trucks = truckMapper.selectByMap(queryMap);
        if (!trucks.isEmpty()) {
            return AjaxResult.error("该车俩下已存在运输车信息，不能删除。");
        }

        removeById(id);
        log.info("删除司机信息成功，id为：{}", id);

        return AjaxResult.success("删除成功！");
    }

    @Override
    public Driver getDriver(String id) {

        Driver driver = getById(id);

        //设置联络员姓名
        if (driver != null && !StringUtils.isEmpty(driver.getUserId())) {
            SysUser sysUser = sysUserService.getById(driver.getUserId());
            if (sysUser != null && !StringUtils.isEmpty(sysUser.getNickName())) {
                driver.setNickName(sysUser.getNickName());
            }
        }

        return driver;
    }

}
